<?php

namespace app\index\controller;

use app\admin\model\Aivideo;
use app\admin\model\SellerCode;
use app\admin\model\SellerLog;
use app\admin\model\StoreShop;
use app\common\controller\Frontend;
use Douyin\Open\ApiException;
use think\Request;

use \app\admin\model\User;
use Douyin\Open\Api\VideoPublishApi;
use Douyin\Open\Api\UserInfoApi;
use Douyin\Open\Model\VideoCreateBody;
use think\Session;
use think\Log;

class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';
    protected $ClientKey;
    protected $ClientSecret;


    public function __construct(Request $request = null)
    {
        parent::__construct($request);
        $this->ClientKey = config('site.ClientKey');
        $this->ClientSecret = config('site.ClientSecret');
    }

    public function index()
    {
        return $this->view->fetch();
    }


    public function douyin($ids = null)
    {

        $param = $this->request->param();

        if ($local_user = Session::get('user')) {

            $access_token = $local_user['access_token'];
            $open_id = $local_user['open_id'];
        }
        elseif (isset($param['access_token'])&&isset($param['open_id']))
        {

            $access_token = $param['access_token'];
            $open_id = $param['open_id'];
            $tmp_user = User::where('open_id', $open_id)->find();
            if($tmp_user){
                $tmp_user->open_token=$access_token;
                $tmp_user->save();
            }
        }

        else {
            $code = $param['code'];
            $redirect_url = "https://open.douyin.com/oauth/access_token/?client_key={$this->ClientKey}&client_secret={$this->ClientSecret}&code={$code}&grant_type=authorization_code";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $redirect_url);//抓取指定网页
            curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);  // 从证书中检查SSL加密算法是否存在

            //执行命令
            $data = curl_exec($ch);
            //关闭URL请求
            curl_close($ch);
            //显示获得的数据

            $data = json_decode($data, true);
            if ($data['data']['error_code'] == 0) {
                $access_token = $data['data']['access_token'];
                $open_id = $data['data']['open_id'];
            }
            $tmp_user = User::where('open_id', $open_id)->find();
            if($tmp_user){
                $tmp_user->open_token=$access_token;
                $tmp_user->save();
            }
        }
        /*  $open_id = "12574b18-f3c5-4af5-9d54-64af4db42d17";
          $access_token = 1;*/
        $aivideos = Aivideo::where('activity_id', $ids)->where('status',2)->select();
        if ($aivideos) {

            $video_number = array_rand($aivideos, 1);

        }
        $model = new \app\admin\model\Activity;
        $row = $model->with(['card', 'manystoreshop'])
            ->find($ids);


        $user = User::where('open_id', $open_id)->find();
        if (!$user) {
            $apiInstance = new UserInfoApi();
            $result = $apiInstance->oauthUserinfoGet($access_token, $open_id);
            $user = new User();
            $user->group_id = 1;
            $user->username = $result['nickname'];
            $user->nickname = $result['nickname'];
            $user->avatar = $result['avatar'];
            $user->gender = $result['gender'];
            $user->open_id = $open_id;
            $user->open_token = $access_token;
            $user->jointime = time();
            $user->manystore_id = $row->manystore_id;
            $user->status = 'normal';
            $user->save();
        }

        $local_user = [
            'user_id' => $user->id,
            'open_id' => $open_id,
            'access_token' => $access_token,
        ];

        Session::set('user', $local_user);



        $tmp_selllog=SellerLog::where('user_id',$user->id)->where('activity_id',$ids)->where('video_id',$aivideos[$video_number]->id)->find();
        if(!$tmp_selllog)
        {
            $tmp_selllog=new SellerLog();
            $tmp_selllog->user_id=$user->id;
            $tmp_selllog->activity_id=$ids;
            $tmp_selllog->video_id=$aivideos[$video_number]->id;
            $tmp_selllog->save();

        }

        $baseurl = $this->request->baseFile(true);
        $redirect_url = $baseurl . "/index/index/mycard";

        if($row->redirect_type==1||$row->paytype==1)
        {
            $store = StoreShop::where('id', $row->manystore_id)->find();
            $redirect_url=$store->douyin_url;

        }
        elseif($row->redirect_type==3)
        {
            $redirect_url=$row->redirect_url;
        }



        $this->view->assign("day", date('Ymd', ($row->card->day_times * 86400) + $row->card->createtime));
        $this->view->assign("row", $row);
        $this->view->assign("video", $aivideos[$video_number]);
        $this->view->assign("access_token", $access_token);
        $this->view->assign("open_id", $open_id);
        $this->view->assign("redirect_url", $redirect_url);



        /* try {
             $apiInstance=new VideoPublishApi();
             $result = $apiInstance->videoUploadPost($aivideos[2]->local, $open_id, $access_token);

             if($result->getData()->getVideo()->getVideoId())
             {
                 $video=$result->getData()->getVideo()->getVideoId();

           $re=$apiInstance->videoCreatePost($open_id, $access_token,(new VideoCreateBody(['video_id'=>$video])));
                 var_dump($re);exit;

             }
         } catch (ApiException $e) {
             echo 'Exception when calling VideoPublishApi->videoUploadPost: ', $e->getMessage(), PHP_EOL;
         }*/


        //}
        $baseurl = $this->request->baseFile(true);
        $mycard_url = $baseurl . "/index/index/mycard";



        $this->view->assign("mycard_url", $mycard_url);


        return $this->view->fetch();


    }


    /**
     * @return mixed
     */
    public  function upload()
    {
        $param = $this->request->param();
        $access_token = $param['access_token'];
        $open_id = $param['open_id'];
        $user = User::where('open_id', $open_id)->find();
        $aivideos = Aivideo::find(['id' => $param['aivideo']]);
        $m_seller = new SellerCode();
        $activity = (new \app\admin\model\Activity)->find($param['ids']);
        if(!$m_seller->where('activity_id', $param['ids'])->where('user_id', $user->id)->find())
        {
            $m_seller->user_id = $user->id;

            $m_seller->activity_id = $aivideos->activity_id;


            $m_seller->code = rand(111111, 999999);
            $m_seller->status = 0;
            $m_seller->save();
        }
        $store = StoreShop::where('id', $activity->manystore_id)->find();
        try {
            $apiInstance = new VideoPublishApi();
            $result = $apiInstance->videoUploadPost($aivideos->local, $open_id, $access_token);
            Log::error([$aivideos->local, $open_id, $access_token]);
            if ($result->getData()->getVideo()->getVideoId()) {
                $video = $result->getData()->getVideo()->getVideoId();

                $body = ['video_id' => $video];
                $body['text']=$aivideos->title;
                if ($store->poi_id) {

                    $body['poi_id'] = $store->poi_id;
                }
                if ($store->address) {
                    $body['text']=$body['text'].',坐标'.$store->address;
                }


                if ($store->openid) {
                    $body['at_users'] = [$store->openid];
                    $body['text']=$body['text'].'@'.$store->name;

                }


                $re = $apiInstance->videoCreatePost($open_id, $access_token, (new VideoCreateBody($body)));

                //兼容客户填错信息
                if(!isset($re['data']['item_id']))
                {
                    $body = ['video_id' => $video];
                    $body['text']=$aivideos->title;
                    $re = $apiInstance->videoCreatePost($open_id, $access_token, (new VideoCreateBody($body)));
                }

                if($video){

                    $tmp_selllog=SellerLog::where('user_id',$user->id)->where('activity_id',$aivideos->activity_id)->where('video_id',$param['aivideo'])->find();
                    $tmp_selllog->video_code=$re['data']['item_id'];
                    $tmp_selllog->type=1;
                    $tmp_selllog->save();
                }


                Log::error($re);
            }
        } catch (ApiException $e) {
            echo 'Exception when calling VideoPublishApi->videoUploadPost: ', $e->getMessage(), PHP_EOL;
        }

        $aivideos->delete();
        return $this->success('获取卡券成功');


    }


    public function mycard()
    {

        $user_id = Session::get('user')['user_id'];

        $m_seller = new SellerCode();
        $model = new \app\admin\model\Activity;
        $cards = $m_seller->where(['user_id' => $user_id, 'status' => 0])->select();

        foreach ($cards as $card) {
            $row = $model->with(['card', 'manystoreshop'])
                ->find($card->activity_id);
            $card->activity = $row;

            $card->day = date('Ymd', ($row->card->day_times * 86400) + $row->card->createtime);

        }

        $this->view->assign("row", $cards);
        return $this->view->fetch();

    }


    public function check($ids = null)
    {


        $model = new \app\admin\model\Activity;


        $url = "https://open.douyin.com/platform/oauth/connect/?client_key=" . $this->ClientKey . "&response_type=code&scope=user_info,video.create&redirect_uri=http://www.ydk1.cn/index/index/douyin/ids/{$ids}";
        $row = $model->with(['card', 'manystoreshop'])
            ->find($ids);
        $this->view->assign("row", $row);
        $this->view->assign("url", $url);
        return $this->view->fetch();


    }

    public function seller($ids = null)
    {

        $param = $this->request->param();

        if ($local_user = Session::get('user')) {

            $access_token = $local_user['access_token'];
            $open_id = $local_user['open_id'];
        }

        elseif (isset($param['access_token'])&&isset($param['open_id']))
        {

            $access_token = $param['access_token'];
            $open_id = $param['open_id'];
            $tmp_user = User::where('open_id', $open_id)->find();
            if($tmp_user){
                $tmp_user->open_token=$access_token;
                $tmp_user->save();
            }
        }
        else {
            $code = $param['code'];
            $redirect_url = "https://open.douyin.com/oauth/access_token/?client_key={$this->ClientKey}&client_secret={$this->ClientSecret}&code={$code}&grant_type=authorization_code";
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $redirect_url);//抓取指定网页
            curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);  // 从证书中检查SSL加密算法是否存在

            //执行命令
            $data = curl_exec($ch);
            //关闭URL请求
            curl_close($ch);
            //显示获得的数据

            $data = json_decode($data, true);
            if ($data['data']['error_code'] == 0) {
                $access_token = $data['data']['access_token'];
                $open_id = $data['data']['open_id'];
            }
            $tmp_user = User::where('open_id', $open_id)->find();
            if($tmp_user){
                $tmp_user->open_token=$access_token;
                $tmp_user->save();
            }
        }
        $user = User::where('open_id', $open_id)->find();

        if(!$user) {
            $msg="您还未领取过核销码";
            $this->view->assign("msg", $msg);
            return $this->view->fetch();
        }

        $where['user_id'] = $user->id;
        $where['activity_id'] = $ids;
        $m_code = new SellerCode();
        $onecode = $m_code->where($where)->find();

        if (!$onecode) {
            $msg="未找到该核销码";
        }

        if ($onecode->status == 1) {
            $msg="该核销码已经被核销过";
        }

        if ($onecode->status == 0) {
            $onecode->status = 1;
            $onecode->save();
            $msg="已核销该核销码";
        }
        $this->view->assign("msg", $msg);
        return $this->view->fetch();
    }



}
